function x=nancorrcoef(X,ntol)

% function x=nancorrcoef(X,ntol)
% computes the pairwise correlation coefficient of the columns of a matrix X, where the elements of
% X might have NaNs, where ntol is the minimum number of observations

for i = 1:size(X,2)
    for j = 1:size(X,2)
        if i~=j
            if size((X(all(isfinite(X(:,[i j])),2),[i j])),1) > ntol
                y = corr(X(all(isfinite(X(:,[i j])),2),[i j]));
                x(i,j) = y(1,2);
            else
                x(i,j) = NaN;
            end
        else
            x(i,j) = 1;
        end
    end
end

